<script setup>
import { ref, onMounted } from 'vue'
import axios from '../utils/axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

// 配置 marked
marked.setOptions({
  highlight: function(code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(code, { language: lang }).value
    }
    return hljs.highlightAuto(code).value
  },
  breaks: true
})

const wrongQuestions = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 添加对话框相关的响应式变量
const reviewDialogVisible = ref(false)
const currentQuestion = ref(null)
const reviewNote = ref('')

// 回顾历史对话框相关
const historyDialogVisible = ref(false)
const reviewHistories = ref([])
const historyLoading = ref(false)
const historyTotal = ref(0)
const historyCurrentPage = ref(1)
const historyPageSize = ref(5)

// 分享对话框相关
const shareDialogVisible = ref(false)
const shareNote = ref('')
const shareLoading = ref(false)

const addToWrongQuestion = async (question) => {
  try {
    const request = {
      questionId: question.id,
      userAnswer: question.userAnswer,
      correctAnswer: question.correctAnswer,
      analysis: question.analysis
    }
    await axios.post('/wrong-questions', request)
    ElMessage.success('添加到备忘录成功')
    await fetchWrongQuestions()
  } catch (error) {
    ElMessage.error('添加失败：' + (error.response?.data?.message || '未知错误'))
  }
}

const renderMarkdown = (text) => {
  try {
    return marked(text || '')
  } catch (e) {
    console.error('Markdown rendering error:', e)
    return text || ''
  }
}

const toggleAnswerExpand = (wrong) => {
  wrong.isExpanded = !wrong.isExpanded
}

const fetchWrongQuestions = async () => {
  loading.value = true
  try {
    const response = await axios.get('/wrong-questions', {
      params: {
        page: currentPage.value - 1,
        size: pageSize.value,
        sort: 'createdAt,desc'
      }
    })
    wrongQuestions.value = response.data.content.map(item => ({
      ...item,
      isExpanded: false,
      renderedAnswer: renderMarkdown(item.correctAnswer)
    }))
    total.value = response.data.totalElements
  } catch (error) {
    console.error('Error fetching wrong questions:', error)
    ElMessage.error('获取错题列表失败：' + (error.response?.data?.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page) => {
  currentPage.value = page
  fetchWrongQuestions()
}

const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这道错题吗？', '提示', {
      type: 'warning'
    })
    await axios.delete(`/wrong-questions/${id}`)
    ElMessage.success('删除成功')
    fetchWrongQuestions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error.response?.data?.message || '未知错误'))
    }
  }
}

const updateWrongQuestion = async (item) => {
  try {
    const request = {
      questionId: item.questionId,
      userAnswer: item.userAnswer,
      correctAnswer: item.correctAnswer,
      analysis: item.analysis
    }
    await axios.put(`/wrong-questions/${item.id}`, request)
    ElMessage.success('更新成功')
  } catch (error) {
    ElMessage.error('更新失败：' + (error.response?.data?.message || '未知错误'))
  }
}

const openReviewDialog = (question) => {
  currentQuestion.value = question
  reviewNote.value = question.reviewNote || ''
  reviewDialogVisible.value = true
}

const submitReview = async () => {
  if (!reviewNote.value.trim()) {
    ElMessage.warning('请输入回顾笔记')
    return
  }

  try {
    await axios.post(`/wrong-questions/${currentQuestion.value.id}/review`, {
      wrongQuestionId: currentQuestion.value.id,
      reviewNote: reviewNote.value
    })
    ElMessage.success('回顾笔记已保存')
    reviewDialogVisible.value = false
    fetchWrongQuestions() // 刷新列表
  } catch (error) {
    console.error('Review error:', error.response?.data)
    ElMessage.error('保存失败：' + (error.response?.data?.message || '未知错误'))
  }
}

// 查看回顾历史
const openHistoryDialog = async (question) => {
  currentQuestion.value = question
  historyDialogVisible.value = true
  historyCurrentPage.value = 1
  await fetchReviewHistory()
}

const fetchReviewHistory = async () => {
  if (!currentQuestion.value) return
  
  historyLoading.value = true
  try {
    const response = await axios.get(
      `/wrong-questions/${currentQuestion.value.id}/review-history`,
      {
        params: {
          page: historyCurrentPage.value - 1,
          size: historyPageSize.value
        }
      }
    )
    reviewHistories.value = response.data.content
    historyTotal.value = response.data.totalElements
  } catch (error) {
    ElMessage.error('获取回顾历史失败：' + (error.response?.data?.message || '未知错误'))
  } finally {
    historyLoading.value = false
  }
}

const handleHistoryPageChange = (page) => {
  historyCurrentPage.value = page
  fetchReviewHistory()
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '未回顾'
  return new Date(dateTime).toLocaleString()
}

// 分享相关方法
const openShareDialog = (question) => {
  currentQuestion.value = question
  shareNote.value = ''
  shareDialogVisible.value = true
}

const shareQuestion = async () => {
  if (!shareNote.value.trim()) {
    ElMessage.warning('请输入分享说明')
    return
  }

  shareLoading.value = true
  try {
    await axios.post('/community/share', {
      wrongQuestionId: currentQuestion.value.id,
      shareNote: shareNote.value
    })
    
    ElMessage.success('分享成功')
    shareDialogVisible.value = false
  } catch (error) {
    console.error('Error sharing question:', error)
    ElMessage.error('分享失败：' + (error.response?.data?.message || '未知错误'))
  } finally {
    shareLoading.value = false
  }
}

const handlePageSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1  // 重置到第一页
  fetchWrongQuestions()
}

onMounted(() => {
  fetchWrongQuestions()
})
</script>

<template>
  <div class="wrong-questions-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>备忘录</span>
        </div>
      </template>

      <div v-if="wrongQuestions.length === 0" class="empty-text">
        暂无错题记录
      </div>
      <template v-else>
        <div v-for="wrong in wrongQuestions" :key="wrong.id" class="wrong-item">
          <el-card>
            <div class="question-content">
              <div class="user-answer">
                <strong>我的问题：</strong>
                <div class="answer-text">{{ wrong.userAnswer }}</div>
              </div>
              
              <div class="correct-answer">
                <strong>正确答案：</strong>
                <div 
                  class="answer-text" 
                  :class="{ 'expanded': wrong.isExpanded }"
                  v-html="wrong.renderedAnswer"
                ></div>
                <el-button 
                  v-if="wrong.correctAnswer && wrong.correctAnswer.length > 300"
                  link 
                  type="primary" 
                  @click="toggleAnswerExpand(wrong)"
                >
                  {{ wrong.isExpanded ? '收起' : '展开' }}
                </el-button>
              </div>

              <div v-if="wrong.analysis" class="analysis">
                <strong>解析：</strong>
                <div class="analysis-text">{{ wrong.analysis }}</div>
              </div>

              <div v-if="wrong.reviewNote" class="review-note">
                <strong>复习笔记：</strong>
                <div class="note-text">{{ wrong.reviewNote }}</div>
              </div>

              <div class="meta-info">
                <span>添加时间：{{ new Date(wrong.createdAt).toLocaleString() }}</span>
                <span>复习次数：{{ wrong.reviewCount }}</span>
                <span v-if="wrong.lastReviewTime">
                  最后复习：{{ new Date(wrong.lastReviewTime).toLocaleString() }}
                </span>
              </div>

              <div class="actions">
                <el-button type="primary" size="small" @click="openReviewDialog(wrong)">
                  复习
                </el-button>
                <el-button type="info" size="small" @click="openHistoryDialog(wrong)">
                  历史
                </el-button>
                <el-button type="success" size="small" @click="openShareDialog(wrong)">
                  分享到社区
                </el-button>
                <el-button type="danger" size="small" @click="deleteWrongQuestion(wrong.id)">
                  删除
                </el-button>
              </div>
            </div>
          </el-card>
        </div>

        <div class="pagination" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </template>
    </el-card>

    <!-- 回顾对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="回顾与思考"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form label-position="top">
        <el-form-item label="问题">
          <div class="dialog-content">{{ currentQuestion?.userAnswer }}</div>
        </el-form-item>
        <el-form-item label="正确答案">
          <div 
            class="dialog-content markdown-content" 
            v-html="currentQuestion?.renderedAnswer"
          ></div>
        </el-form-item>
        <el-form-item label="回顾笔记">
          <el-input
            v-model="reviewNote"
            type="textarea"
            :rows="4"
            placeholder="请输入您的回顾笔记..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview">
            保存笔记
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 回顾历史对话框 -->
    <el-dialog
      v-model="historyDialogVisible"
      title="回顾历史记录"
      width="60%"
      :close-on-click-modal="false"
    >
      <div v-loading="historyLoading">
        <!-- 只在有历史记录时显示问题信息和历史列表 -->
        <template v-if="reviewHistories.length > 0">
          <div class="history-question-info">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="问题">
                <div class="dialog-content">{{ currentQuestion?.userAnswer }}</div>
              </el-descriptions-item>
              <el-descriptions-item label="正确答案">
                <div 
                  class="dialog-content markdown-content" 
                  v-html="currentQuestion?.renderedAnswer"
                ></div>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="history-list">
            <el-timeline>
              <el-timeline-item
                v-for="history in reviewHistories"
                :key="history.id"
                :timestamp="formatDateTime(history.createdAt)"
                type="primary"
              >
                <el-card class="history-card">
                  {{ history.reviewNote }}
                </el-card>
              </el-timeline-item>
            </el-timeline>

            <div class="pagination-container" v-if="historyTotal > historyPageSize">
              <el-pagination
                v-model:current-page="historyCurrentPage"
                :page-size="historyPageSize"
                :total="historyTotal"
                layout="prev, pager, next"
                @current-change="handleHistoryPageChange"
              />
            </div>
          </div>
        </template>
        <el-empty v-else description="暂无回顾记录" />
      </div>
    </el-dialog>

    <!-- 添加分享对话框 -->
    <el-dialog
      v-model="shareDialogVisible"
      title="分享到社区"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form label-position="top">
        <el-form-item label="问题">
          <div class="dialog-content">{{ currentQuestion?.userAnswer }}</div>
        </el-form-item>
        <el-form-item label="正确答案">
          <div 
            class="dialog-content markdown-content" 
            v-html="currentQuestion?.renderedAnswer"
          ></div>
        </el-form-item>
        <el-form-item label="分享说明">
          <el-input
            v-model="shareNote"
            type="textarea"
            :rows="4"
            placeholder="请输入分享说明，例如：这道题的解题思路、遇到的困难、心得体会等..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shareDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="shareQuestion"
            :loading="shareLoading"
          >
            确认分享
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.wrong-questions-container {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
}

.wrong-item {
  margin-bottom: 20px;
}

.question-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.user-answer,
.correct-answer,
.analysis,
.review-note {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.answer-text {
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 300px;
  overflow: hidden;
  transition: max-height 0.3s ease;
}

.answer-text.expanded {
  max-height: none;
}

.meta-info {
  display: flex;
  gap: 15px;
  color: #909399;
  font-size: 12px;
}

.actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* Markdown 样式 */
:deep(.answer-text) {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
}

:deep(.answer-text pre) {
  margin: 0;
  padding: 16px;
  overflow-x: auto;
  background-color: #f3f4f5;
  border-radius: 4px;
}

:deep(.answer-text code) {
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
  font-size: 14px;
}

:deep(.answer-text p) {
  margin: 8px 0;
}

:deep(.answer-text ul),
:deep(.answer-text ol) {
  padding-left: 20px;
}

:deep(.answer-text table) {
  border-collapse: collapse;
  width: 100%;
  margin: 8px 0;
}

:deep(.answer-text th),
:deep(.answer-text td) {
  border: 1px solid #dcdfe6;
  padding: 8px;
  text-align: left;
}

:deep(.answer-text th) {
  background-color: #f5f7fa;
}

:deep(.answer-text blockquote) {
  margin: 8px 0;
  padding: 8px 16px;
  border-left: 4px solid #409eff;
  background-color: #ecf5ff;
}

.history-question-info {
  margin-bottom: 20px;
}

.history-list {
  margin-top: 20px;
}

.history-card {
  margin-left: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.dialog-content {
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-word;
}

.markdown-content {
  max-height: 400px;
  overflow-y: auto;
}

:deep(.markdown-content) {
  /* 继承之前定义的 Markdown 样式 */
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
}

.el-tooltip__trigger {
  display: inline-flex;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 